<?php

/**
 * IndexController - The default controller class
 * 
 * @author
 * @version 
 */

class SearchLuceneController extends Zend_Controller_Action 
{
    public function init() {
        $config = Zend::initConfig('Search/Lucene');
        if ($config->enable) {
            Zend_Registry::set('luceneEncoding', $config->encoding);
            //$luceneIndex = Zend_Search_Lucene::open(PROJECT_ROOT . $config->folder);
            $luceneIndex = Zend_Search_Lucene::create(PROJECT_ROOT . $config->folder);
            Zend_Registry::set('luceneIndex', $luceneIndex);
        }
    }

	/**
	 * The default action - show the home page
	 */
    public function indexAction() 
    {
        $this->render();
    }

    public function listAction() {
        
        if ($this->getRequest()->isPost()) {
            
            $keywords = $this->getRequest()->getParam('keywords');
            
            if (!empty($keywords)) {

                $functionPost = new Core_Model_Function_Post();
                $posts = $functionPost->findAll();

                $luceneIndex = Zend_Registry::get('luceneIndex');
                $encoding = Zend_Registry::get('luceneEncoding');

                foreach ($posts as $post) {
                    $doc = new Zend_Search_Lucene_Document();
                    $doc->addField(Zend_Search_Lucene_Field::UnIndexed('post_id', $post['post_id'], $encoding));
                    //$doc->addField(Zend_Search_Lucene_Field::Text('post_title', $post['post_title'], $encoding));
                    $doc->addField(Zend_Search_Lucene_Field::Keyword('post_title', $post['post_title'], $encoding));
                    //$doc->addField(Zend_Search_Lucene_Field::Text('post_content', $post['post_content'], 'ISO-8859-1'));
                    $doc->addField(Zend_Search_Lucene_Field::Text('post_content', $post['post_content'], $encoding));
                    $doc->addField(Zend_Search_Lucene_Field::UnStored('post_date_create', $post['post_date_create'], $encoding));
                    $luceneIndex->addDocument($doc);
                }
                $luceneIndex->optimize();

                Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding($encoding);
                $term = new Zend_Search_Lucene_Index_Term('*'.$keywords.'*');
                $queryString = new Zend_Search_Lucene_Search_Query_Wildcard($term);

                $hits = $luceneIndex->find($queryString);
                $result = false;
                if (is_array($hits) and !empty($hits)) {
                    $result = $hits;
                }
                $this->view->result = $result;
            }
        }
    }
}